<template>
  <div>
    <!-- 头部状态栏 -->
    <van-nav-bar title="本会议审批明细" left-text="返回" left-arrow @click-left="onClickLeft" />
    <!-- <van-cell title="选择单个日期" :value="date" @click="show = true" /> -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="van_card">
        <div class="van_card_title eventnumber">会议编号：{{eventid}}</div>
        <van-row class="van_card_title">
          <van-col span="24">已出票人数:{{allsp[1]}}</van-col>
          <van-col span="24">报名人数:{{allsp[3]}}人 异地人数:{{allsp[4]}}人</van-col>
        </van-row>
        <van-row class="van_card_title">
          <van-col span="8">已用额度:</van-col>
          <van-col span="8">
            <van-progress
              stroke-width="8px"
              :show-pivot="false"
              :percentage="hasRate<0?0:hasRate"
              :color="hasRate<80?'#1989fa':'#FB304D'"
            />
          </van-col>
          <van-col class="rate_num">{{hasRate}}%</van-col>
        </van-row>
        <van-notice-bar
          wrapable
          mode="closeable"
        >为大交通（机票、火车票）实际出票金额占用的额度，通过FASCO邮箱线下出票的占用额度情况会在次日更新。</van-notice-bar>
      </div>
      <QuickSearch :quickSearch="quickSearch" @getSearchInfo="filterList"></QuickSearch>
      <van-tabs v-model="active">
        <van-tab title="已提交审批" class="mrBot">
          <template #title>
            <van-badge
              v-if="waitapprovalList.length"
              color="#1989fa"
              :content="waitapprovalList.length"
            >
              <div class="badge_container">已提交审批</div>
            </van-badge>
          </template>
          <ApprovalmeetDetail
            :meetingDetail="waitapprovalList"
            :showAllCheck="true"
            :eventid="eventid"
          ></ApprovalmeetDetail>
          <div class="block"></div>
        </van-tab>

        <van-tab title="已审批">
          <template #title>
            <van-badge
              v-if="agreeapprovalList.length"
              color="#1989fa"
              :content="agreeapprovalList.length"
            >
              <div class="badge_container">已审批</div>
            </van-badge>
          </template>
          <ApprovalmeetDetail :meetingDetail="agreeapprovalList" :eventid="eventid"></ApprovalmeetDetail>
        </van-tab>
        <van-tab title="已拒绝">
          <template #title>
            <van-badge v-if="rejectapprovalList.length" :content="rejectapprovalList.length">
              <div class="badge_container">已拒绝</div>
            </van-badge>
          </template>
          <ApprovalmeetDetail
            :showCancel="true"
            :meetingDetail="rejectapprovalList"
            :eventid="eventid"
          ></ApprovalmeetDetail>
        </van-tab>
      </van-tabs>
      <transition name="van-slide-up">
        <div v-if="active===0" class="approval_fixed_btn">
          <van-button plain type="info" @click="ApproveRocheTR(false)">拒绝审批</van-button>
          <van-button type="info" @click="ApproveRocheTR(true)">通过审批</van-button>
        </div>
      </transition>
    </van-pull-refresh>
  </div>
</template>

<script>
import ApprovalmeetDetail from "../components/approvalmeetDetail";
import QuickSearch from "../components/quickSearch";
import apilist from "../utils/apiList";
export default {
  data() {
    return {
      show: false,
      isCheck: false,
      active: 0,
      isLoading: false,
      approvalList: [],
      showSelect: false,
      calenderStatus: 0,
      eventid: "",
      info: "",
      quickSearch: {
        name: "",
        deadline: "",
      },
      waitapprovalList: [],
      agreeapprovalList: [],
      rejectapprovalList: [],
      all_loading: [],
      hasuse: 0,
      totalFare: 0,
      hasRate: 0,
      allsp: [[], 0, 0, 0, 0],
      tr_num: [1, 0, 0],
      event: {},
    };
  },
  created() {
    let eventid1 = JSON.parse(sessionStorage.getItem("eventid"));
    // let currentActive = sessionStorage.getItem("currentActive");
    // this.active = currentActive?JSON.parse(currentActive):0;
    // sessionStorage.removeItem("currentActive")
    this.eventid = this.$route.query.eventid || eventid1;
    this.info = this.$route.query.info;
    this.getMeetingDetail();
    this.getRateOf();
  },
  methods: {
    // 拒绝审批
    refuse() {
      this.$notify({
        type: "success",
        message: "审批成功",
        duration: 1000,
      });
    },
    onRefresh() {
      window.location.reload();
    },
    // 获取当前会议详情
    async getMeetingDetail() {
      const NextDay = this.endDate || new Date().getnextday("yyyy-MM-dd");
      const myDate = new Date();
      const startDate =
        this.startDate ||
        new Date(myDate.getTime() - 1000 * 60 * 60 * 24 * 30).format(
          "yyyy-MM-dd"
        );
      const res = await this.$axios.get(
        apilist[1] +
          "/GetStaffTripsByEventID?eventid=" +
          this.eventid +
          "&start=" +
          startDate +
          "&end=" +
          NextDay
      );
      let p = res.data;
      const res2 = await this.$axios.get(
        apilist[0] + "/GetAttendeeListByEventid?eventid=" + this.eventid
      );
      let attending = res2.data;
      attending.map((ve, ie) => {
        if (ve.HCPCity && ve.HCPCompanyCity && ve.SignedID != "D") {
          // if(ve.HCPCity!=_this.event.Place&&ve.HCPCompanyCity!=_this.event.Place){
          this.allsp[4]++;
        }
      });
      this.allsp[3] = res2.data.filter(function (v, i, arr) {
        return v.SignedID != "D";
      }).length;
      let all_psg = [];
      let allprice = 0;
      for (let ind = p.length - 1; ind >= 0; ind--) {
        let v = p[ind];

        attending.forEach((attend, index) => {
          if (attend.UCICode == v.ExorderList[0].PaxStaffNo) {
            v.hospital = attend.HCPHospital;
            // console.log(attend);
          }
        });
        let allcancel = true;
        var login = JSON.parse(
          sessionStorage.getItem("login") || sessionStorage.getItem("manage")
        );
        let oe = v.ExorderList;
        let au_dl = "";
        let all_tripsn = [];
        let f1 = [];
        let h1 = [];
        let t1 = [];
        let if_allc = true;
        let alx = [0, 0, 0, 0];
        v.orderFare = 0;
        for (let i = oe.length - 1; i >= 0; i--) {
          if (!v.Status && oe[i].OrderStatus.indexOf("未确认") > -1) {
            v.Status = "已提交审批";
          }
          if (oe[i].OrderStatus == "已取消") {
            // oe.splice(i,1);
            au_dl = "";
          } else {
            if_allc = false;
          }
          v.orderFare += oe[i].TotalSellAmount * 1;
          if (oe[i].ProductType == "FDR1") {
            //oe[i].OrderStatus=='已取消'||
            alx[1]++;
          } else if (oe[i].ProductType == "FDIR") {
            alx[2]++;
          } else if (
            (oe[i].ProductType == "FDI" && v.Status != "已提交审批") ||
            (v.Status == "已审批" && oe[i].OrderStatus == "已出票")
          ) {
            alx[0]++;
          }
          if (
            oe[i].OrderStatus == "已取消" ||
            (v.Status == "已拒绝" &&
              oe[i].ProductType == "FDI" &&
              v.Status != "已提交审批")
          ) {
            alx[3]++;
          }
          if (all_tripsn.indexOf(oe[i].CltTravelerName) == -1)
            all_tripsn.push(oe[i].CltTravelerName);
          if (oe[i].FreecancelDeadline) {
            let tf = new Date(
              oe[i].FreecancelDeadline.replace(/-/g, "/")
            ).getTime();
            if (!au_dl) au_dl = tf;
            if (tf < au_dl) au_dl = tf;
          }
          if (oe[i].ProductCat.toLowerCase() == "f") {
            f1.push(oe[i]);
          }
          if (oe[i].ProductCat.toLowerCase() == "h") {
            h1.push(oe[i]);
          }
          if (oe[i].ProductCat.toLowerCase() == "t") {
            t1.push(oe[i]);
          }
        }
        if (if_allc) v.Status = "已拒绝";
        if (v.Status == "已提交审批") {
          // v.Status = '待审批';
          v.isCheck = false;
          this.waitapprovalList.push(v);
        } else if (v.Status == "已审批") {
          this.allsp[0].push(v);
          if (all_psg.indexOf(oe[0].CltTravelerName) == -1) {
            all_psg.push(oe[0].CltTravelerName);
          }
          this.agreeapprovalList.push(v);
        } else if (v.Status == "已拒绝") {
          this.rejectapprovalList.push(v);
        }
        v.deadline = "";
        if (au_dl) v.deadline = new Date(au_dl).format("yyyy-MM-dd hh:mm");
        v.name = all_tripsn[0];
        v.fAmount = f1.length;
        v.tAmount = t1.length;
        v.alx = alx;
      }
      this.allsp[1] = this.allsp[0].length;
      this.allsp[1] = all_psg.length;
      this.allsp[0].map((vv, ii) => {
        this.allsp[2] += vv.ExorderList.length;
        vv.ExorderList.map((vi, iv) => {
          allprice += vi.TotalSellAmount * 1;
        }); //if(vi.OrderStatus!='已取消')
      });
      this.approvalList = p;
      if (p.length == 0) {
        this.tr_num = [0, 0, 0];
      }
      let allp =
        (login &&
          !!login.EventBudgetList[0] &&
          login.EventBudgetList[0].BudgetAmount) ||
        0;
      // if(!allp)allp = 0;
      allprice = allprice;
      if (!allp) {
        allp = 1111111110;
        allprice = 0;
      }
    },
    // 获取费用使用额度
    async getRateOf() {
      const res = await this.$axios.get(
        apilist[1] + "/GetRocheEventFee?eventid=" + this.eventid
      );
      if (res.status == 200) {
        this.hasuse = res.data > 0 ? res.data : 0;
      }
      const res1 = await this.$axios.get(
        apilist[0] + "/GetEvent?eventid=" + this.eventid
      );
      this.event = res1.data;
      sessionStorage.setItem("event", JSON.stringify(res1.data));
      if (res1.status == 200) {
        this.totalFare = res1.data.EventBudgetList.length
          ? res1.data.EventBudgetList[0].BudgetAmount
          : 0;
      }
      this.hasRate = this.totalFare
        ? Math.floor((this.hasuse / this.totalFare) * 100)
        : 0;
    },
    // 取当前显示分类数组
    getcurrentList(res) {
      res.forEach((v, z) => {
        if (v.Status === "已提交审批") {
          this.waitapprovalList.push(v);
        } else if (v.Status === "已审批") {
          this.agreeapprovalList.push(v);
        } else if (v.Status === "已拒绝") {
          this.rejectapprovalList.push(v);
        }
      });
    },
    // 筛选当前数组
    filterList(search) {
      this.waitapprovalList = [];
      this.agreeapprovalList = [];
      this.rejectapprovalList = [];
      let hasfilterList = this.approvalList;
      hasfilterList = hasfilterList.filter((v) => {
        const searchDeadLine =
          new Date(search.deadline).getTime() + 1 * (1000 * 60 * 60 * 24);
        const approvelDeadLine = new Date(
          v.deadline.replace(/-/g, "/")
        ).getTime();
        return (
          (search.name ? v.name.indexOf(search.name) !== -1 : true) &&
          (searchDeadLine ? searchDeadLine >= approvelDeadLine : true)
        );
      });
      this.getcurrentList(hasfilterList);
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    // 审批功能
    ApproveRocheTR: function (e) {
      let _this = this;
      let checkList = [];
      let orderLength = this.waitapprovalList.length;
      this.waitapprovalList.map(function (item) {
        if (item.isCheck) {
          console.log(item);
          checkList.push(item);
        }
      });
      if (checkList.length == 0) {
        _this.$notify({
          type: "warning",
          message: "请选择至少一个行程",
          duration: 1000,
        });
        return;
      }
      _this.all_loading = [];
      if (e) {
        let budget = _this.event.EventBudgetList[0].BudgetAmount;
        _this.getcost(this.event.IDNo, function (cost) {
          checkList.map(function (z, o) {
            let p = z.ExorderList;
            p.map(function (v, i) {
              cost += v.TotalSellAmount * 1;
            });
          });
          // console.log(cost);
          if (cost > budget) {
            _this.$notify({
              type: "warning",
              message: "当前会议的大交通使用额度已超过预算，请尽快更新预算",
            });
            return;
          } else {
            _this.ApproveRocheTR0(e, checkList);
          }
        });
      } else {
        _this.ApproveRocheTR0(e, checkList);
      }
      return;

      // _this.
    },
    getcost: function (eventid, fn) {
      this.$axios
        .get(apilist[1] + "/GetRocheEventFee?eventid=" + eventid)
        .then(function (res) {
          res.data = res.data > 0 ? res.data : 0;
          if (fn) {
            fn(res.data);
          }
        })
        .catch(function (e) {});
    },
    ApproveRocheTR0: function (e, checkList) {
      var _this = this;
      checkList.map(function (z, o) {
        _this.all_loading[o] = [];
        var p = z.ExorderList;
        p.map(function (v, i) {
          _this.all_loading[o][i] = false;
          var fnx = e ? _this.ApproveRocheTR2 : _this.ApproveRocheTR3;
          fnx(v, i, o, function (st) {
            var alls = true;
            var all_false = true;
            _this.all_loading.map(function (vv, ii) {
              vv.map(function (vvv, iii) {
                if (!vvv) alls = false;
                if (vvv != "false") all_false = false;
              });
            });
            if (alls) {
              if (all_false) {
                _this.$notify({
                  type: "danger",
                  message: "提交失败",
                  duration: 1000,
                });
                return;
              }
              _this.$notify({
                type: "success",
                message: "提交成功",
                duration: 1000,
              });
              // _this.ApproveRocheTR4(e);
              //_this.$router.go(0);
              window.location.reload();
            }
          });
        });
      });
    },
    ApproveRocheTR2: function (v, i, o, fn) {
      let _this = this;
      this.$axios
        .get(apilist[1] + "/ApproveRocheTR?ex_no=" + v.No)
        .then(function (res) {
          _this.all_loading[o][i] = true;
          //console.log(res,_this);=='success'
          //_this.loading = false;
          if (res.data && fn) {
            // sessionStorage.setItem("currentActive", JSON.stringify(1));
            fn();
          }
        })
        .catch(function (error) {
          // _this.loading = false;
          _this.all_loading[o][i] = "false";
          if (fn) {
            fn();
          }
        });
    },
    ApproveRocheTR3: function (v, i, o, fn) {
      let _this = this;
      this.$axios
        .get(apilist[1] + "/UnApproveExorder?exno=" + v.No)
        .then(function (res) {
          _this.all_loading[o][i] = true;
          //console.log(res,_this);=='success'
          //_this.loading = false;
          if (res.data && fn) {
            // sessionStorage.setItem("currentActive", JSON.stringify(2));
            fn();
          }
        })
        .catch(function (error) {
          _this.all_C[i] = "false";
          if (fn) {
            fn();
          }
        });
    },
  },
  components: {
    ApprovalmeetDetail,
    QuickSearch,
  },
};
</script>

<style lang="less" scoped>
.all_check {
  padding: 15px 15px 0px 15px;
  .app_meetDe_item_right {
    text-align: right;
  }
  .icon_filter {
    position: relative;
    top: 2px;
  }
}
.van-progress {
  top: 9px;
}
.rate_num {
  margin-left: 5px;
  color: #666666;
  transform: scale(0.85);
}
.van-notice-bar--wrapable {
  font-size: 12px;
  height: auto;
  padding: 4px 9px;
}
</style>